package com.ywjt.platformbusiness.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.core.content.PermissionChecker;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.ywjt.platformbusiness.EventBusBean;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends BaseActivity {
    private static final int REQUEST_CODE = 101;
    private static final int REQUSETCODE=102;
    private int from = 0;
    private NoScrollViewPager vpContent;
    private BottomNavigationView navigation;
    private MainPageController pageController;
    boolean isExit = false;//退出程序标识
    private String apkUrl="";
    @Override
    protected void init(Bundle savedInstanceState) { setAndroidNativeLightStatusBar(true); }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_main;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        from = getIntent().getIntExtra("from", 0);
        vpContent = findViewById(R.id.vpContent);
        pageController = new MainPageController(MainActivity.this, vpContent);
        navigation = findViewById(R.id.navigation);
        //修改为原图片颜色
        navigation.setItemIconTintList(null);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        switch (from) {
            case 0:
                navigation.setSelectedItemId(R.id.navigation_home);
                break;
            case 1:
                navigation.setSelectedItemId(R.id.navigation_classify);
                break;
            case 2:
                navigation.setSelectedItemId(R.id.navigation_cart);
                break;
            case 3:
                navigation.setSelectedItemId(R.id.navigation_my);
                break;
        }

      //  getAppInfo();
        pageController.ChangePage(from);
        setAndroidNativeLightStatusBar(true);
    }



    @RequiresApi(api = Build.VERSION_CODES.M)
    @Subscribe()
    public void change(EventBusBean eventBus){
        switch (eventBus.getCode()){
            case 101:
                navigation.setSelectedItemId(R.id.navigation_classify);
                pageController.ChangePage(1);
                break;
        }
    }


    /****权限**/
    private void checkPermission(){
        try{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (PermissionChecker.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED
                        || PermissionChecker.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED
                        || PermissionChecker.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)!= PermissionChecker.PERMISSION_GRANTED||
                PermissionChecker.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_COARSE_LOCATION)!=PermissionChecker.PERMISSION_GRANTED||
                        PermissionChecker.checkSelfPermission(MainActivity.this,Manifest.permission.READ_PHONE_STATE)!=PermissionChecker.PERMISSION_GRANTED) {
                    // 不相等 请求授权
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.REQUEST_INSTALL_PACKAGES
                            ,Manifest.permission.CAMERA
                            ,Manifest.permission.ACCESS_COARSE_LOCATION
                            ,Manifest.permission.READ_PHONE_STATE
                    },REQUEST_CODE);
                }else {
                    //dialog.changeView();
                    downloadAPK(apkUrl);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("aaa", "onRequestPermissionsResult: " +
                            "权限申请成功");
                    for (int i : grantResults) {
                        Log.d("aaa", "onRequestPermissionsResult: " + i);
                    }
                    downloadAPK(apkUrl);
                } else {
                    Toast.makeText(MainActivity.this, "您已拒绝申请权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }
    @Override
    protected void initData() { }

    @Override
    public int getTitleBarType() {
        return TITLEBAR_NULL;
    }

    /**
     * from = 0，首页
     * @param context
     * @param i
     */
    public static void actionStart(Context context, int i) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("from", i);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(!EventBus.getDefault().isRegistered(this)){//加上判断
            EventBus.getDefault().unregister(this);
        }
    }

    /**
     * 底部导航栏点击事件
     */
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    from = 0;
                    pageController.ChangePage(0);
                    setAndroidNativeLightStatusBar(true);
                    return true;
                case R.id.navigation_classify:
                    from = 1;
                    pageController.ChangePage(1);
                    setAndroidNativeLightStatusBar(true);
                    return true;
                case R.id.navigation_cart:
                    from = 2;
                    pageController.ChangePage(2);
                    setAndroidNativeLightStatusBar(true);
                    return true;
                case R.id.navigation_my:
                    from = 3;
                    pageController.ChangePage(3);
                    setAndroidNativeLightStatusBar(true);
                    return true;
            }
            return false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            switch (from) {
                case 0:
                    exitByDoubleClick();
                    break;
                case 1:
                case 2:
                case 3:
                    from = 0;
                    navigation.setSelectedItemId(R.id.navigation_home);
                    setAndroidNativeLightStatusBar(true);
                    break;
            }
        }
        return false;
    }

    //双击返回退出
    private void exitByDoubleClick() {
        Timer tExit = null;
        if (!isExit) {
            isExit = true;
            Toast.makeText(this, "再返回一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;//取消退出
                }
            }, 2000);// 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

//    AppUpdateDialog dialog;
//    public void loadNewVersionAlertDiaLog(){
//        dialog=new AppUpdateDialog(MainActivity.this);
//        dialog.setClicklistener(new AppUpdateDialog.ClickListenerInterface() {
//            @Override
//            public void confirm() {
//                checkPermission();
//            }
//        });
//        dialog.show(getSupportFragmentManager());
//    }

    /**
     * 获取版权信息
     **/
//    public  void getAppInfo() {
//        new HttpRequest(getContext()).doGet(UrlConstants.userInfo_getVersion, null,new HttpStringCallBack() {
//            @Override
//            public void onSuccess(Object result) {
//                try {
//                    String data = result.toString();
//                    //把请求得数据转换成json对象
//                    JSONObject jsonObject = null;
//                    jsonObject = new JSONObject(data);
//                    String message = jsonObject.getString("message");
//                    int code=jsonObject.getInt("code");
//                    if(code==200) {
//                        Object obj = JsonUtils.fromJson(result.toString(), VersionMode.class);
//                        if (obj instanceof VersionMode) {
//                            VersionMode model = (VersionMode) obj;
//                            if (APKVersionCodeUtils.getVersionCode(MainActivity.this) < Integer.parseInt(model.getResult().getVersion())) {
//                                //有更高的版本
//                                apkUrl=model.getResult().getUrl();
//                                loadNewVersionAlertDiaLog();
//                            }
//                        }
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(int code, String msg) {
//            }
//        });
//    }

    private String mSavePath="";
    //  判断是否停止
    private boolean mIsCancel = false;
    /**
     * 下载APk
     * @param apk_file_url
     */
    private void downloadAPK(final String apk_file_url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                        String sdPath = Environment.getExternalStorageDirectory() + "/";
//                      文件保存路径
                        mSavePath = sdPath + "oil";
                        File dir = new File(mSavePath);
                        if (!dir.exists()){
                            dir.mkdir();
                        }
                        // 下载文件
                        HttpURLConnection conn = (HttpURLConnection) new URL(apk_file_url).openConnection();
                        conn.connect();
                        InputStream is = conn.getInputStream();
                        int length = conn.getContentLength();

                        File apkFile = new File(mSavePath, "tzy.apk");
                        FileOutputStream fos = new FileOutputStream(apkFile);
                        int count = 0;
                        byte[] buffer = new byte[1024];
                        while (!mIsCancel){
                            int numread = is.read(buffer);
                            count += numread;
                            // 更新进度条
                            mUpdateProgressHandler.sendEmptyMessage(1);
                            // 下载完成
                            if (numread < 0){
                                mUpdateProgressHandler.sendEmptyMessage(2);
                                break;
                            }
                            fos.write(buffer, 0, numread);
                        }
                        fos.close();
                        is.close();
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /**
     * 接收消息
     */
    @SuppressLint("HandlerLeak")
    private Handler mUpdateProgressHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                   // dialog.changeUI(1);
                    break;
                case 2:
                    // 隐藏当前下载对话框
                    //dialog.changeUI(2);
                    installAPK();
            }
        };
    };

    /**
     * 安装Apk
     */
    private void installAPK() {
        File apkFile = new File(mSavePath, "tzy.apk");
        if (!apkFile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (null != apkFile) {
            try {
                //兼容7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".fileprovider", apkFile);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    //兼容8.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        boolean hasInstallPermission = this.getPackageManager().canRequestPackageInstalls();
                        if (!hasInstallPermission) {
                            startInstallPermissionSettingActivity();
                            //dialog.dismiss();
                            return;
                        }
                    }
                } else {
                    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
                if (getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                    startActivity(intent);
                   // dialog.dismiss();
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Uri packageURI = Uri.parse("package:"+getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //startActivity(intent);
        startActivityForResult(intent,REQUSETCODE);
    }


}